import request from "@/service/request";
import { isNotEmpty3 } from "./validate";
import { saveAs } from 'file-saver';
import {datetimeFormat} from "@/utils/datetimeFormat.ts";
/**
 * converts an object into a URL-encoded string,
 *   only one layer of nested object can be used
 *
 * @param params: object to convert
 * @returns: an URL-encoded string
 */
export const tansParams = (params: any): string => {
  let result = '';
  for (const propName of Object.keys(params)) {
    const value = params[propName];
    const part = encodeURIComponent(propName) + '=';
    if (isNotEmpty3(value)) {
      // nested object (only one layer)
      if (typeof value === 'object') {
        for (const key of Object.keys(value)) {
          if (isNotEmpty3(value[key])) {
            const params = propName + '[' + key + ']';
            const subPart = encodeURIComponent(params) + '=';
            result += subPart + encodeURIComponent(value[key]) + '&';
          }
        }
      } else {  // primitives
        result += part + encodeURIComponent(value) + '&';
      }
    }
  }
  return result;
};

/**
 * 验证是否为blob格式
 * @param data
 */
const blobValidate = (data:any) => {
  return data.type !== 'application/json'
}

/**
 * 通用下载方法
 * @param url
 * @param params
 * @param filename
 */
export function download(url: any, params: any, filename: any) {
  // downloadLoadingInstance = Loading.request({ text: "正在下载数据，请稍候", spinner: "el-icon-loading", background: "rgba(0, 0, 0, 0.7)", })
  return request
    .post(url, params, {
      transformRequest: [
        (params) => {
          return tansParams(params);
        },
      ],
      headers: { "Content-Type": "application/x-www-form-urlencoded" },
      responseType: "blob",
    })
    .then(async (data) => {
      const isBlob = blobValidate(data);
      if (isBlob) {
        const blob = new Blob([data as any]);
        saveAs(blob, filename);
      } else {
        // const resText = await data.text();
        // const rspObj = JSON.parse(resText);
        // const errMsg = errorCode[rspObj.code] || rspObj.msg || errorCode['default']
        // Message.error(errMsg);
      }
      // downloadLoadingInstance.close();
    })
    .catch((r) => {
      console.error(r);
      // downloadLoadingInstance.close();
    });
}

/**
 * 将日期数组，转换为可以直接请求的日期对象
 * @param timeRange
 */
export const convertTimeRange = (
  timeRange: Array<Date | null>,
): {
  beginTime: string | null;
  endTime: string | null;
} => {
  const beginTime: string | null =
    timeRange[0] != null ? datetimeFormat(timeRange[0]) : null;
  const endTime: string | null =
    timeRange[1] != null ? datetimeFormat(timeRange[1]) : null;

  return { beginTime, endTime };
};
